package com.fwtai.service.web;

import com.fwtai.bean.PageFormData;
import com.fwtai.config.ConfigFile;
import com.fwtai.service.core.MenuService;
import com.fwtai.tool.IdBuilder;
import com.fwtai.tool.ToolClient;
import com.fwtai.tool.ToolJWT;
import com.fwtai.web.UserAccountDao;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 系统用户业务层
 * @作者 田应平
 * @版本 v1.0
 * @QQ号码 444141300
 * @创建日期 2021-07-21 17:49:27
 * @官网 <url>http://www.fwtai.com</url>
*/
@Service
public class UserAccountService{

  private final UserAccountDao useraccountDao;

  private final BCryptPasswordEncoder passworder;

  private final ThreadPoolTaskExecutor taskExecutor;

  private final MenuService menuService;

  public UserAccountService(final UserAccountDao useraccountDao,final BCryptPasswordEncoder passworder,final ThreadPoolTaskExecutor taskExecutor,final MenuService menuService){
    this.useraccountDao = useraccountDao;
    this.passworder = passworder;
    this.taskExecutor = taskExecutor;
    this.menuService = menuService;
  }

  public String add(final HttpServletRequest request){
    final PageFormData formData = new PageFormData(request);
    final String p_user_name = "user_name";
    final String p_password = "password";
    final String validate = ToolClient.validateField(formData,p_user_name,p_password);
    if(validate != null)return validate;
    if(formData.getString("user_name").length() > 64){
      return ToolClient.createJsonFail("登录账号字数太长");
    }
    if(formData.getString("password").length() > 64){
      return ToolClient.createJsonFail("账号密码字数太长");
    }
    formData.put("kid",new IdBuilder().getId121L());
    formData.put("type",2);
    return ToolClient.executeRows(useraccountDao.add(formData));
  }

  public String edit(final HttpServletRequest request){
    final PageFormData formData = new PageFormData(request);
    final String p_kid = "kid";
    final String p_user_name = "user_name";
    final String p_password = "password";
    final String validate = ToolClient.validateField(formData,p_user_name,p_password,p_kid);
    if(validate != null)return validate;
    if(formData.getString("user_name").length() > 64){
      return ToolClient.createJsonFail("登录账号字数太长");
    }
    final String password = formData.getString("password");
    if(password.length() > 64){
      return ToolClient.createJsonFail("账号密码字数太长");
    }
    final String exist_key = useraccountDao.queryExistById(formData.getString(p_kid));
    if(exist_key == null){
      return ToolClient.createJsonFail("数据不存在,刷新重试");
    }
    formData.put("password",passworder.encode(password));
    return ToolClient.executeRows(useraccountDao.edit(formData));
  }

  public String queryById(final PageFormData formData){
    final String p_id = "id";
    final String validate = ToolClient.validateField(formData,p_id);
    if(validate != null)return validate;
    return ToolClient.queryJson(useraccountDao.queryById(formData.getString(p_id)));
  }

  public String listData(PageFormData formData){
    try {
      formData = ToolClient.dataTableMysql(formData);
      if(formData == null)return ToolClient.jsonValidateField();
      final HashMap<String,Object> map = useraccountDao.listData(formData);
      return ToolClient.dataTableOK((List<Object>)map.get(ConfigFile.rows),map.get(ConfigFile.total));
    } catch (Exception e){
      return ToolClient.dataTableException(formData.get("sEcho"));
    }
  }

  public String editEnabled(final PageFormData formData){
    final String p_disable = "disable";
    final String p_enabled = "enabled";
    final String p_userId = "userId";
    final String validate = ToolClient.validateField(formData,p_disable,p_enabled,p_userId);
    if(validate != null)return validate;
    final String fieldInteger = ToolClient.validateInteger(formData,p_disable,p_enabled);
    if(fieldInteger != null)return fieldInteger;
    final String kid = formData.getString(p_userId);
    final String user_name = useraccountDao.queryExistById(kid);//查询是否存在
    if(user_name == null){
      return ToolClient.createJsonFail("账号已不存在");
    }
    final int rows = useraccountDao.editEnabled(formData);
    return ToolClient.executeRows(rows);
  }

  public String queryLogin(final Long userId){
    return CompletableFuture.supplyAsync(()->{
      if(userId == null){
        return ToolClient.jsonValidateField();
      }
      //查询用户是否存在或是否已被禁用
      final Integer enabled = useraccountDao.queryLogin(userId);
      if(enabled == null){
        return ToolClient.createJsonFail("账号已被删除,刷新重试");
      }
      if(enabled == 1){
        return ToolClient.createJsonFail("账号已被禁用,无法登录");
      }
      final String uid = String.valueOf(userId);
      final String menuData = menuService.getMenuData(uid);
      final List<HashMap<String,String>> btnRows = menuService.getBtnRows(uid);
      final HashMap<String,Object> map = new HashMap<>(2);
      map.put(ConfigFile.REFRESH_TOKEN,ToolJWT.expireRefreshToken(uid));
      map.put(ConfigFile.ACCESS_TOKEN,ToolJWT.expireAccessToken(uid));
      map.put("btnRows",btnRows);
      map.put("menuData",menuData);
      return ToolClient.queryJson(map);
    },taskExecutor).join();
  }

  public String editCategory(final HttpServletRequest request,final Integer category){
    return CompletableFuture.supplyAsync(()->{
      final PageFormData formData = new PageFormData(request);
      final String p_kid = "kid";
      final String validate = ToolClient.validateField(formData,p_kid);
      if(validate != null)return validate;
      final String exist_key = useraccountDao.queryExistById(formData.getString(p_kid));
      if(exist_key == null){
        return ToolClient.createJsonFail("数据不存在,刷新重试");
      }
      final Long kid = formData.getLong(p_kid);
      return ToolClient.executeRows(useraccountDao.editCategory(kid,category));
    },taskExecutor).join();
  }
}